#include <iostream>
#include <unistd.h>
#include <cerrno>
#include <string>
#include <string.h>
#include <cassert>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
using namespace std;
int main()
{
    //1.创建管道
    int pipefd[2]={0};
    int ret=pipe(pipefd);
    if(ret<0)
    {
    cout<<"pipe error:"<<errno<<"->"<<strerror(errno)<<endl;
    return -1;
    }
    cout<<"pipefd[0]:"<<pipefd[0]<<endl;
    cout<<"pipefd[1]:"<<pipefd[1]<<endl;

    //2.创建子进程
    pid_t pid=fork();
    assert(pid!=-1);
    if(pid==0)
    {
        //子进程
        //3.关闭不需要的fd，让父进程进行读取，子进程进行写入
        close(pipefd[0]);
        //4.开始通信
        string namestr="我是子进程";
        int cnt=1;
        char buf[1024];
        while(true)
        {
            /*snprintf(buf,sizeof(buf),"%s,cnt:%d,我的pid是%d",namestr.c_str(),cnt++,getpid());
            write(pipefd[1],buf,strlen(buf));*/
            //sleep(10);
            char c='X';
            write(pipefd[1],&c,1);
            cout<<cnt++<<endl;
            //sleep(1);
            /*if(cnt==5)
            {
                break;
            }*/
            sleep(1);
        }
        close(pipefd[1]);
        exit(0);
    }
    //父进程
    //3.关闭不需要的fd，让父进程进行读取，子进程进行写入
    close(pipefd[1]);
    //4.开始通信
    char buf[1024];
    while(true)
    {
        //sleep(10);
        int ret=read(pipefd[0],buf,sizeof(buf)-1);
        if(ret>0)
        {
            buf[ret]='\0';
            cout<<"我是父进程，我接受到子进程的信息："<<buf<<endl;
        }
        else if(ret==0)
        {
            cout<<"父进程读到了文件结尾"<<endl;
            break;
        } 
        else
        {
            cout<<"读取失败"<<endl;
            break;
        }
        sleep(5);
        break;
    }
    close(pipefd[0]); 
    int status;
    waitpid(pid,&status,0);
    cout<<"sign:"<<(status&0x7F)<<endl;
    return 0;
}
